package com.simpletour.qa.service.filter;

import com.simpletour.qa.service.util.UserUtil;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Order(1)
@WebFilter(filterName = "UserFilter", urlPatterns = "/*")
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String userId = httpServletRequest.getHeader("userId");
            UserUtil.setCurrentUserId(Integer.parseInt(userId));
        } catch (NumberFormatException e) {

        } finally {
            chain.doFilter(request, response);
            UserUtil.removeCurrentUserId();
        }
    }

    @Override
    public void destroy() {

    }
}
